$(function(){
	layui.use('form', function(){
		layer = layui.layer;
		form = layui.form;
		var name = '请选择';
		$('.sunSelect').each(function(){
			var url = $(this).attr('data-url');
			var upid = 0;
			var obj = $(this);
			$(this).find('[lay-filter=sunSelect]').each(function(i){
				getSelect(obj, upid, i, '1');
				upid = $(this).attr('data-id');
			})
		})

		form.on('select(sunSelect)', function(data){
			var obj = $(data.elem);
			var parent = obj.parents('.sunSelect');
			var parent_index = parent.index('.sunSelect');
			var i = obj.index('.sunSelect:eq(' + parent_index + ') [lay-filter=sunSelect]');

			//清空后面的
			parent.find('[lay-filter=sunSelect]:gt(' + i + ')').html('<option value="">'+name+'</option>');
			var ts = ['441900', '442000', '460400'];
			if(i){

			}
			//更新下一个
			getSelect(parent, data.value, i + 1);
		})

		//公共方法
		function getSelect(box, upid, index, is_create){
			var obj = box.find('[lay-filter=sunSelect]:eq(' + index + ')');
			var data_id = is_create == '1' ? obj.attr('data-id') : '';
			if(upid >= 0 && upid!==''){
				var url = box.attr('data-url');
				$.get(
					url,
					{id: upid,level:obj.attr('data-level')},
					function(data){
						createSelect(obj, data, box.attr('data-value'), box.attr('data-name'), data_id);
					}, 'json'
				)
			}else{
				obj.html('<option value="">'+obj.attr('data-name')+'</option>');
				form.render();
			}
		}

		function createSelect(obj, data, data_value, data_name, data_id){
			var options = '<option value="">'+obj.attr('data-name')+'</option>';
			$.each(data, function(i){
				var selected = data_id == data[i][data_value] ? 'selected' : '';
				options += '<option value="' + data[i][data_value] + '" ' + selected + '>' + data[i][data_name] + '</option>';
			})
			obj.html(options);
			form.render();
		}
	})
})